<template>
  <UploadExcel
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
  ></UploadExcel>
</template>

<script>
import { reqAddEmployeeBatch } from "@/api/employees";
export default {
  name: "Import",
  data() {
    return {};
  },
  created() {
    console.log(this.$route.query.type);
  },
  methods: {
    formatExcelDate(numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1); // 毫秒
      time.setYear(time.getFullYear() - 70);
      const year = time.getFullYear() + "";
      const month = time.getMonth() + 1 + "";
      const date = time.getDate() - 1 + "";
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? "0" + month : month) +
          format +
          (date < 10 ? "0" + date : date)
        );
      }
      return (
        year +
        (month < 10 ? "0" + month : month) +
        (date < 10 ? "0" + date : date)
      );
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (isLt1M) {
        return true;
      }

      this.$message({
        message: "Please do not upload files larger than 1m in size.",
        type: "warning",
      });
      return false;
    },
    handleSuccess({ results, header }) {
      console.log(results, header);
      if (this.$route.query.type === "user") {
        this.handleAddEmployeeBatch(results, header);
      }
      if (this.$route.query.type === "money") {
        console.log("工资的批量导入");
      }
      if (this.$route.query.type === "social") {
        console.log("社保的批量导入");
      }
    },
    async handleAddEmployeeBatch(results, header) {
      const userRelations = {
        入职日期: "timeOfEntry",
        手机号: "mobile",
        姓名: "username",
        转正日期: "correctionTime",
        工号: "workNumber",
      };
      const arr = [];
      results.forEach((item) => {
        const obj = {};
        for (const key in item) {
          const englishKey = userRelations[key];
          // englishKey === "timeOfEntry" || englishKey === "correctionTime"
          if (['timeOfEntry','correctionTime'].includes(englishKey)) {
            obj[englishKey] = this.formatExcelDate(item[key], "-");
          } else {
            obj[englishKey] = item[key];
          }
        }
        arr.push(obj);
      });
      console.log(arr);
      //   this.tableData = results;
      //   this.tableHeader = header;
      const res = await reqAddEmployeeBatch(arr);
      console.log(res);
      this.$message.success("批量导入员工成功");
      this.$router.push("/employees");
    },
  },
};
</script>

<style>
</style>